//
//  StarMyViewController.m
//  LiveStar
//
//  Created by 漪珊 on 2016/12/9.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "StarMyViewController.h"
#import "GuardRankViewController.h"
#import "StarAccountViewController.h"
#import "StarSendPresentListController.h"
#import "StarCooperationViewController.h"
#import "LoginViewController.h"
#import "StarPredictAndVideoListController.h"
#import "StarFileViewController.h"
#import "FStarTrendViewController.h"
#import "StarDetailView.h"
#import "StarMyCell.h"
#import "LogoutCell.h"
#import "StarInfoGuardCell.h"

@interface StarMyViewController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate,LogoutCellDelegate,StarDetailViewDelegate>{
    NSMutableDictionary *_starInfoDict;
    NSMutableDictionary *_starStatusDict;
    NSMutableArray *_userImgArray;

}
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong) StarDetailView *topView;
@property (nonatomic, copy) NSString *imageFile;
@property (nonatomic, copy) NSString *imagePath;
@end

@implementation StarMyViewController
static NSString *logoutCell = @"logoutCell";

#pragma mark -- 明星我的请求
- (void)starMyRequest {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:KStarMine];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            _starStatusDict = responseObject[@"data"];
            _starInfoDict = responseObject[@"data"][@"star"];
            NSArray *imgArray = _starStatusDict[@"guard"][@"list"];
            for (int i = 0; i<imgArray.count; i++) {
                NSDictionary *userDict = imgArray[i];
                [_userImgArray addObject:userDict[@"u_avatar"]];
                if (i == 3) break;
            }
            [self setUpData];
            [self.tableView reloadData];
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}

#pragma mark --  退出登录发送请求
- (void)LogoutRequest {
    NSDictionary *dict = @{
                           @"udid":User_ID,
                           @"token":TOKEN
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kAccount_Logout];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        [LSFileCacheManager removeObjectByFileName:kUserPath];
        [LSFileCacheManager removeObjectByFileName:kLOG_TOKEN];
        [self pushToLog];
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}

//更换背景图片
- (void)uploadImageRequestWithImage:(UIImage *)image {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kUploadImage];
    QZHUploadFormData *uploadData = [[QZHUploadFormData alloc] init];
    uploadData.imageData = UIImageJPEGRepresentation(image, 0.5);
    uploadData.dataType = DataTypeJpeg;
    uploadData.name = @"img";
    uploadData.fileName = @"image.jpg";
    [NetworkTools UploadRequestWithParams:dict UrlString:urlString uploadParams:uploadData successBlock:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            self.imageFile = responseObject[@"data"][@"file"];
            self.imagePath = responseObject[@"data"][@"path"];
            [self ChangeBackImageRequest];
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}
- (void)ChangeBackImageRequest {
    NSDictionary *dict = @{@"udid":User_ID,
                           @"token":TOKEN,
                           @"path":self.imagePath,
                           @"file":self.imageFile
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kStarBackImg];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        if ([responseObject[@"code"] intValue] == 200) {
            
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self starMyRequest];
    
    [self setNav];
    
    [self setUpUI];
    
    // Do any additional setup after loading the view.
}

#pragma mark -- NAV

- (void)setNav {
    self.navigationController.view.backgroundColor = [UIColor navagationBarColor];
}

#pragma mark -- UI
- (void)setUpUI {
    _starInfoDict = [NSMutableDictionary dictionaryWithCapacity:1];
    _starStatusDict = [NSMutableDictionary dictionaryWithCapacity:1];
    _userImgArray = [NSMutableArray arrayWithCapacity:1];
    [self creatTableView];
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)creatTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT-kTABBAE_HEIGHT) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor colorWithHexString:@"F7F8F9"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.topView = [[NSBundle mainBundle] loadNibNamed:@"StarDetailView" owner:self options:nil].lastObject;
    
    self.topView.delegate = self;
    self.topView.backBtn.hidden = YES;
    self.tableView.tableHeaderView = self.topView;
    [self.topView.starImgView sd_setImageWithURL:[NSURL URLWithString:[LSUserInfoManager sharedManager].currentUserInfo.u_avatar] placeholderImage:kPlACE_ICON];
    self.topView.starName.text = [LSUserInfoManager sharedManager].currentUserInfo.u_nickname;
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
}

- (void)setUpData {
    [self.topView.backImage sd_setImageWithURL:[NSURL URLWithString:_starInfoDict[@"s_backdrop"]] placeholderImage:nil];
    [self.topView.starImgView sd_setImageWithURL:[NSURL URLWithString:_starInfoDict[@"u_avatar"]] placeholderImage:nil];
    self.topView.starName.text = _starInfoDict[@"s_name"];
    self.topView.focusedNum.text = [NSString stringWithFormat:@"被关注:%@",_starInfoDict[@"s_booked"]];
    self.topView.popularity.text = [NSString stringWithFormat:@"人气:%@",_starInfoDict[@"u_obtain"]];
    self.topView.liveID.text = [NSString stringWithFormat:@" LSID : %@ ",_starInfoDict[@"s_udid"]];
    self.topView.predictNums.text = KString(_starStatusDict[@"advance"]);
    self.topView.videoNums.text = KString(_starStatusDict[@"playBack"]);
    self.topView.trendNums.text = KString(_starStatusDict[@"circle"]);
    if ([_starStatusDict[@"live"] intValue]) {
        self.topView.liveStateBtn.hidden = NO;
    } else {
        self.topView.liveStateBtn.hidden = YES;
    }
    self.topView.starTag1.text = [NSString stringWithFormat:@" %@ ",_starInfoDict[@"s_musictype"]];
}
#pragma mark -- tableView 代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        StarInfoGuardCell *cell = [StarInfoGuardCell loadNibCellWithTabelView:tableView];
        cell.popularNumsLabel.text = KString(_starStatusDict[@"guard"][@"num"]);
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.dataArray = _userImgArray;
        return cell;

    }
    if (indexPath.row == 5) {
        LogoutCell *cell = [tableView dequeueReusableCellWithIdentifier:logoutCell];
        if (!cell) {
            cell = [[LogoutCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:logoutCell];
        }
        cell.delegate = self;
        return cell;

    } else {
        StarMyCell *cell = [StarMyCell loadNibCellWithTabelView:tableView];
        cell.textLabel.font = UIFont(14);
        if (indexPath.row == 1) {
            cell.titleLabel.text = @"我的账户";
        } else if (indexPath.row == 2) {
            cell.titleLabel.text = @"送出的礼品";
        } else if (indexPath.row == 3) {
            cell.titleLabel.text = @"商家礼品合作";
        } else if (indexPath.row == 4) {
            cell.titleLabel.text = @"明星小档案";
        }
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        GuardRankViewController *rankVC = [[GuardRankViewController alloc] init];
        rankVC.s_uid = User_ID;
        [self.navigationController pushViewController:rankVC animated:YES];
    } else if (indexPath.row == 1) {
        StarAccountViewController *accountVc = [StarAccountViewController new];
        [self.navigationController pushViewController:accountVc animated:YES];
    } else if (indexPath.row == 2) {
        StarSendPresentListController *listVc = [[StarSendPresentListController alloc] init];
        listVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:listVc animated:YES];
    } else if (indexPath.row == 3) {
        StarCooperationViewController *cooperVc = [[StarCooperationViewController alloc] init];
        cooperVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:cooperVc animated:YES];
    } else if (indexPath.row == 4) {
        StarFileViewController *fileVC = [[StarFileViewController alloc] init];
        fileVC.name = [LSUserInfoManager sharedManager].currentUserInfo.u_nickname;
        fileVC.userType = UserTypeStars;
        [self.navigationController pushViewController:fileVC animated:YES];
    }
}

#pragma mark --退出登录
- (void)logout {
    UIAlertController *alertVc = [UIAlertController  alertControllerWithTitle:@"温馨提示" message:@"您确认退出登录吗?" preferredStyle:UIAlertControllerStyleAlert] ;
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self LogoutRequest];
        
    }];
    [alertVc addAction:action1];
    [alertVc addAction:action2];
    [self presentViewController:alertVc animated:YES completion:nil];
}

- (void)pushToLog {
    QZHNavgationController *nav = [[QZHNavgationController alloc] initWithRootViewController:[LoginViewController new]];
    [UIApplication sharedApplication].keyWindow.rootViewController = nav;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 5) {
        return 77;
    }
    return 50*kScale;
}

#pragma mark -- StarDetailViewDelegate
- (void)ItemClickWithTag:(NSUInteger)tag {
    switch (tag) {
        case 1:{//预告
            StarPredictAndVideoListController *listVC = [[StarPredictAndVideoListController alloc] init];
            listVC.listType = PredictListType;
            [self.navigationController pushViewController:listVC animated:YES];
        }
            break;
        case 2:{//回放
            StarPredictAndVideoListController *listVC = [[StarPredictAndVideoListController alloc] init];
            listVC.listType = VideoListType;
            [self.navigationController pushViewController:listVC animated:YES];
        }
            break;
        case 3:{//动态
            FStarTrendViewController *trendVC = [[FStarTrendViewController alloc] init];
            [self.navigationController pushViewController:trendVC animated:YES];
        }
            break;
        case 4:{//修改背景图片
            [self changeBackImg];
        }
            break;
            
        default:
            break;
    }
}


- (void)changeBackImg {
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"选择照片方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
        
    }];
    
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        /**
         其实和从相册选择一样，只是获取方式不同，前面是通过相册，而现在，我们要通过相机的方式
         */
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        //获取方式:通过相机
        PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
        PickerImage.allowsEditing = YES;
        PickerImage.delegate = self;
        [self presentViewController:PickerImage animated:YES completion:nil];
    }];
    
    UIAlertAction *photos = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        //获取方式1：通过相册（呈现全部相册），UIImagePickerControllerSourceTypePhotoLibrary
        //获取方式2，通过相机，UIImagePickerControllerSourceTypeCamera
        //获取方法3，通过相册（呈现全部图片），UIImagePickerControllerSourceTypeSavedPhotosAlbum
        PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //允许编辑，即放大裁剪
        PickerImage.allowsEditing = YES;
        //自代理
        PickerImage.delegate = self;
        //页面跳转
        [self presentViewController:PickerImage animated:YES completion:nil];
    }];
    [alertVc addAction:camera];
    [alertVc addAction:photos];
    [alertVc addAction:cancle];
    [self presentViewController:alertVc animated:YES completion:nil];
}

#pragma mark -- 图片选择代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //定义一个newPhoto，用来存放我们选择的图片。
    UIImage *IconImage = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    self.topView.backImage.image = IconImage;
    [self uploadImageRequestWithImage:IconImage];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
